"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Checkbox } from "@/components/ui/checkbox"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { FileText, AlertCircle, CheckCircle } from "lucide-react"
import type { Contact } from "./columns"

interface ExportDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  contacts: Contact[]
  selectedContacts: Contact[]
  onExport: (format: string, contactIds?: number[]) => Promise<void>
}

export function ExportDialog({ 
  open, 
  onOpenChange, 
  contacts, 
  selectedContacts, 
  onExport 
}: ExportDialogProps) {
  const [format, setFormat] = useState("csv")
  const [exportAll, setExportAll] = useState(true)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)

  const handleExport = async () => {
    setLoading(true)
    setError(null)
    setSuccess(null)

    try {
      const contactIds = exportAll ? undefined : selectedContacts.map(c => c.id)
      
      if (!exportAll && (!contactIds || contactIds.length === 0)) {
        throw new Error("请选择要导出的联系人")
      }

      await onExport(format, contactIds)
      setSuccess(`成功导出 ${exportAll ? contacts.length : selectedContacts.length} 个联系人`)
      
      // 延迟关闭对话框
      setTimeout(() => {
        onOpenChange(false)
        setSuccess(null)
      }, 2000)

    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "导出失败")
    } finally {
      setLoading(false)
    }
  }

  const handleClose = () => {
    setError(null)
    setSuccess(null)
    onOpenChange(false)
  }

  const formatDescription = {
    csv: "CSV格式，适合在Excel中打开和编辑",
    json: "JSON格式，适合程序处理和备份"
  }

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>导出联系人</DialogTitle>
          <DialogDescription>
            选择导出格式和范围
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          {/* 导出范围 */}
          <div className="space-y-3">
            <Label>导出范围</Label>
            <div className="space-y-2">
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="export-all"
                  checked={exportAll}
                  onCheckedChange={(checked) => setExportAll(!!checked)}
                />
                <Label htmlFor="export-all" className="text-sm font-normal">
                  导出所有联系人 ({contacts.length} 个)
                </Label>
              </div>
              <div className="flex items-center space-x-2">
                <Checkbox
                  id="export-selected"
                  checked={!exportAll}
                  onCheckedChange={(checked) => setExportAll(!checked)}
                />
                <Label htmlFor="export-selected" className="text-sm font-normal">
                  仅导出选中的联系人 ({selectedContacts.length} 个)
                </Label>
              </div>
            </div>
          </div>

          {/* 导出格式 */}
          <div className="space-y-2">
            <Label>导出格式</Label>
            <Select value={format} onValueChange={setFormat}>
              <SelectTrigger>
                <SelectValue placeholder="选择格式" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="csv">CSV格式</SelectItem>
                <SelectItem value="json">JSON格式</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-sm text-muted-foreground">
              {formatDescription[format as keyof typeof formatDescription]}
            </p>
          </div>

          {/* 格式说明 */}
          <Alert>
            <FileText className="h-4 w-4" />
            <AlertDescription>
              {format === 'csv' ? (
                <div>
                  <p className="font-medium mb-1">CSV格式说明：</p>
                  <ul className="text-sm space-y-1">
                    <li>• 包含表头：姓名, 电话, 邮箱, 公司, 职位, 地址, 分组, 标签, 生日, 备注, 收藏, 创建时间</li>
                    <li>• 标签用逗号分隔</li>
                    <li>• 收藏显示为"是"或"否"</li>
                    <li>• 可直接在Excel中打开</li>
                  </ul>
                </div>
              ) : (
                <div>
                  <p className="font-medium mb-1">JSON格式说明：</p>
                  <ul className="text-sm space-y-1">
                    <li>• 包含完整的联系人信息</li>
                    <li>• 支持所有字段，包括社交账号</li>
                    <li>• 适合程序处理和备份</li>
                    <li>• 可重新导入到系统中</li>
                  </ul>
                </div>
              )}
            </AlertDescription>
          </Alert>

          {/* 错误提示 */}
          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {/* 成功提示 */}
          {success && (
            <Alert>
              <CheckCircle className="h-4 w-4" />
              <AlertDescription>{success}</AlertDescription>
            </Alert>
          )}
        </div>

        <DialogFooter>
          <Button type="button" variant="outline" onClick={handleClose}>
            取消
          </Button>
          <Button onClick={handleExport} disabled={loading}>
            {loading ? "导出中..." : "导出"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
